package com.demo.service.impl;

import com.demo.TestApplication;
import com.demo.mapper.TestMapper;
import com.demo.pojo.User;
import com.demo.service.TestService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class TestServiceImpl implements TestService {
    public static final String LOCK_DEMO = "lock1";

    @Autowired
    private TestMapper testMapper;

    @Override
    public int updateMoney(Integer id, double money) {
        int i = testMapper.addLock(LOCK_DEMO);
        if (i > 0) {
            TestApplication.logger.info(Thread.currentThread().getName() + "获取了锁：" + i);
            try {
                //查询用户余额
                User user = testMapper.getUser(id);
                Double userMoney = user.getMoney();
                if (userMoney >= money) {
                    //余额足
                    return testMapper.updateMoney(id, money);
                }
            } finally {
                //无论如何都要释放锁
                testMapper.deleteLock(LOCK_DEMO);
            }
        }
        return -1;
    }
}
